/**
 * @Author: easten
 * @Created: 2024-04-15 23:29:48
 * @Description: iot历史数据组件
 *
 */
import classnames from "classnames";
import React, { useState, useEffect, useMemo } from "react";
import { CpuIcon, FileExcelIcon } from "tdesign-icons-react";
import {
  Button,
  DateRangePicker,
  DateRangePickerProps,
  DateRangeValue,
  MessagePlugin,
  Select,
  Space,
  Table,
  Tag,
  Tree,
} from "tdesign-react";
import { ModuleCommonProps, PageParams, TreeDataModel } from "_common/DataType";
import {
  IotDevice,
  IotDeviceGroup,
  IotHistory,
  IotStation,
  IotTerminal,
} from "_common/entity";
import {
  ApiDeviceGroup,
  ApiHistory,
  ApiPoint,
  ApiStation,
  ApiTerminal,
} from "_common/api/iot";
import { GetColumns, TableTitle } from "components";
import HistoryDrawer from "./HistoryDrawer";
import dayjs from "dayjs";
import _ from "lodash";
import { downloadFile } from "utils/downloadUtil";
export type IotHistoryCompProps = ModuleCommonProps & {
  treeType: "station" | "device"; // 树结构的模式，站点模式和设备模式，站点模式主要通过站点查询当前站点下的设备，进行数据的统计
  // 禁用导出
  disableExport?: boolean;
};
const IotHistoryComp: React.FC<IotHistoryCompProps> = (props) => {
  const { axios, className, treeType, disableExport } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [dataList, setDataList] = useState<IotHistory[]>([]);
  const [selectedRow, setSelectedRow] = useState<IotHistory>();
  const [deviceList, setDeviceList] = useState<IotDevice[]>([]);
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  // 定义总页数
  const [total, setTotal] = useState<number>();

  const [visible, setVisible] = useState(false);
  const [deviceTree, setDeviceTree] = useState<TreeDataModel[]>([]);
  const [selectNode, setSelectNode] = useState<TreeDataModel | undefined>();
  const [terminals, setTerminals] = useState<IotTerminal[]>([]);
  const [products, setProducts] = useState<IotDeviceGroup[]>([]);
  // 站点列表
  const [stationData, setStationData] = useState<IotStation[]>([]);

  // 定义时间范围
  const [startTime, setStartTime] = useState<string>();
  const [endTime, setEndTime] = useState<string>();

  // 定义默认的时间值，前一天+当天 []
  const [timeRange, setTimeRange] = useState<DateRangeValue>([
    dayjs().subtract(2, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ]);

  const apiHistory = new ApiHistory(axios);
  // const apiDevice = new ApiDevice(axios);
  const apiTerminal = new ApiTerminal(axios);
  const apiProduct = new ApiDeviceGroup(axios);
  const apiStation = new ApiStation(axios);
  const apiPoint = new ApiPoint(axios);

  useEffect(() => {
    // getTree();
    apiTerminal.getTerminalList().then((res) => {
      setTerminals(res.data);
    });

    apiProduct.getDeviceGroupList().then((res) => {
      setProducts(res.data);
    });
  }, []);

  useEffect(() => {
    // deviceList 按dtCode 进行分组

    if (treeType == "station") {
      // 查询站点，设施、设备
      apiStation.getList().then((res) => {
        setStationData(res.data);
      });
    } else {
      let group = _.groupBy(deviceList, "dtCode");
      if (!products) return;
      if (group) {
        let treeArr: TreeDataModel[] = [];
        _.forEach(group, (value, key) => {
          let _children = value?.map((a) => {
            return {
              label: a.deviceName,
              value: a.deviceCode,
              type: 2,
              data: a,
            };
          }) as TreeDataModel[];
          let tree: TreeDataModel = {
            label:
              products?.find((item) => item?.groupCode == Number(key))
                ?.groupName ?? "",
            value: key,
            children: _children,
            type: 1,
          };
          treeArr.push(tree);
        });
        setDeviceTree(treeArr);
      }
    }
  }, [deviceList, products, treeType]);

  const getHistory = async () => {
    if (selectNode && selectNode.type == 1) {
      MessagePlugin.error("请选择设备");
      return;
    }
    let _stime = undefined;
    let _etime = undefined;
    if (startTime && startTime != "undefined") {
      _stime = startTime;
    }
    if (endTime && endTime != "undefined") {
      _etime = endTime;
    }
    const response = await apiHistory.getPage({
      pageNum: pageState.pageNum,
      pageSize: pageState.pageSize,
      deviceCode:
        treeType == "station" ? selectNode?.deviceCode : selectNode?.value,
      startTime: _stime,
      endTime: _etime,
    });

    if (response && response.code == 200 && response.data) {
      setDataList(response.data.list);
      setTotal(response.data.total);
      /* setPageState({
        ...pageState,
        total: ,
      }); */
    } else {
      setDataList([]);
    }
  };

  useEffect(() => {
    getHistory();
  }, [selectNode, startTime, endTime, pageState.pageNum, pageState.pageSize]);

  const onChange: DateRangePickerProps["onChange"] = (value) => {
    setTimeRange(value);
    setStartTime(String(value[0]));
    setEndTime(String(value[1]));
  };

  // 获取结构树

  const renderLabel = (node: any) => {
    let data = node.data;
    if (data.type == 1) {
      return (
        <Tag
          theme="warning"
          variant="outline"
          icon={<CpuIcon color="#EF9735" />}
          size="small"
        >
          {data.label}
        </Tag>
      );
    } else {
      return treeType == "station" ? (
        <Tag theme="success" variant="outline" size="small">
          {data.label}【{data?.deviceCode}】
        </Tag>
      ) : (
        <Tag theme="success" variant="outline" size="small">
          {data.label}:{data?.value}
        </Tag>
      );
    }
  };

  const treeNode = useMemo(() => {
    return (
      <Tree
        data={deviceTree}
        scroll={{ type: "lazy" }}
        style={{
          maxHeight: "calc(100vh - 240px)",
          overflowY: "auto",
        }}
        activable
        hover
        transition
        label={renderLabel}
        className="device-tree ml-0"
        onActive={(e, c) => {
          if (e.length == 0) {
            setSelectNode(undefined);
          } else {
            setSelectNode(c.node.data as TreeDataModel);
          }
        }}
      />
    );
  }, [deviceTree, selectNode]);

  // 表头
  const columns = useMemo(() => {
    return GetColumns(
      treeType == "station" ? 109 : selectNode?.data?.dtCode,
      pageState
    );
  }, [pageState, selectNode, treeType]);

  // 终端列表等
  const terminalSelectNode = useMemo(() => {
    console.log("terminals:", terminals);
    return terminals?.map((a) => {
      return {
        label: a.terminalName,
        value: a.id,
      };
    });
  }, [terminals]);

  // 站点列表
  const stationNode = useMemo(() => {
    return stationData?.map((a) => {
      return {
        label: a.name,
        value: a.id,
      };
    });
  }, [stationData]);

  // 导出历史数据
  const exportHistory = async () => {
    let _stime = dayjs().subtract(2, "day").format("YYYY-MM-DD");
    let _etime = dayjs().format("YYYY-MM-DD");
    if (startTime && startTime != "undefined") {
      _stime = startTime;
    }
    if (endTime && endTime != "undefined") {
      _etime = endTime;
    }
    let _code =
      treeType == "station" ? selectNode?.deviceCode : selectNode?.value;
    let url =
      axios.defaults.baseURL +
      "/api/iot/export/export-fat-history?deviceCode=" +
      _code +
      "&startTime=" +
      _stime +
      "&endTime=" +
      _etime;
    downloadFile(url, _code + "-历史数据.xlsx");
  };

  // 下载所有设备数据
  const exportAllDevice = async () => {
    let url = axios.defaults.baseURL + "/api/iot/export/export-device-list";
    downloadFile(url, "加脂设备统计表.xlsx");
  };
  return (
    <div className={classnames(className, "flex", "flex-row h-full")}>
      <div
        style={{
          width: 300,
          borderRight: "1px solid var(--td-border-level-1-color)",
        }}
        className="h-full"
      >
        <TableTitle text={treeType == "station" ? "站点信息" : "设备信息"} />
        <div className="pt-4 pr-5 pl-0 device-tree-container">
          <div className="mb-5 ">
            <Select
              placeholder="请选择"
              onChange={(v) => {
                if (treeType == "station") {
                  // 根据选中的站点ids进行查询
                  apiPoint.getDeviceByStation(Number(v)).then((res) => {
                    console.log("res.data:", res.data);
                    setDeviceTree(res.data);
                  });
                } else {
                  setDeviceList(
                    terminals?.find((a) => a.id == Number(v))?.devices ?? []
                  );
                }
              }}
              options={treeType == "station" ? stationNode : terminalSelectNode}
            />
          </div>
          {treeNode}
        </div>
      </div>
      <div
        className={classnames("pl-5")}
        style={{ width: "calc(100% - 300px)" }}
      >
        <div className="flex flex-row justify-between mb-4">
          <TableTitle text="历史数据" />
          <Space size={5}>
            <DateRangePicker
              allowInput
              clearable
              onChange={onChange}
              value={timeRange}
            />
            <Button
              onClick={() => {
                getHistory();
              }}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                if (!selectNode) {
                  MessagePlugin.error("请选择设备");
                  return;
                }
                setVisible(true);
              }}
            >
              历史曲线
            </Button>
            {disableExport ? null : (
              <>
                <Button
                  variant="outline"
                  theme="primary"
                  icon={<FileExcelIcon />}
                  onClick={exportHistory}
                >
                  导出当前设备记录
                </Button>
                <Button
                  variant="outline"
                  theme="success"
                  icon={<FileExcelIcon />}
                  onClick={exportAllDevice}
                >
                  导出所有设备
                </Button>
              </>
            )}
          </Space>
        </div>
        <Table<IotHistory>
          bordered
          data={dataList}
          columns={columns}
          loading={loading}
          rowKey="id"
          verticalAlign="middle"
          hover
          pagination={{
            pageSize: pageState.pageSize,
            total: total,
            current: pageState.pageNum,
            showJumper: true,
            onCurrentChange(current) {
              setPageState({
                ...pageState,
                pageNum: current,
              });
            },
            onPageSizeChange(size) {
              setPageState({
                ...pageState,
                pageSize: size,
              });
            },
          }}
        />
      </div>
      <HistoryDrawer
        open={visible}
        treeType={treeType}
        axios={axios}
        device={selectNode}
        value={selectedRow}
        startTime={startTime}
        endTime={endTime}
        onSuccess={() => {
          setVisible(false);
        }}
      />
    </div>
  );
};

export default IotHistoryComp;
